package Network

import (
	"SQL/db"
	"logs"
	"strconv"
)

type group struct {
	GroupID   string
	Nickname  string
	GroupIcon string
}

func getGroupList(clientID string, args interface{}) (response *ServerResponse) {
	code := Success
	msg := ""
	var res interface{}
	defer func() {
		if code != Success {
			logs.Print("code: ", code, " msg: ", msg)
		}
		response = &ServerResponse{
			Method:  "/getGroupList",
			Code:    code,
			Message: msg,
			Result:  res,
		}
	}()
	argsname := []string{"pageIndex", "pageSize"}
	msg, code, argsmap := initargs(args, argsname)
	if code != Success {
		return
	}
	userID := clientID
	pageIndex, _ := strconv.Atoi(argsmap["pageIndex"].(string))
	pageSize, _ := strconv.Atoi(argsmap["pageSize"].(string))
	sql := "select *from users where id= $1"
	rows, err := db.RowQuery(sql, userID)
	if err != nil {
		logs.Print(err.Error())
		msg = err.Error()
		code = errDBQueryFailed
		return
	}
	defer rows.Close()

	if rows.Next() == false {
		msg = "该用户不存在"
		code = errAccountNotExist
		return
	}
	sql = "select id,nickname,iconurl from objects,members where members.groupid =objects.id and members.userid = $1 order by id asc limit $2 offset $3 "
	offset := pageIndex * pageSize
	var objs []interface{}
	objs = append(objs, userID, pageSize, offset)
	rows, err = db.RowQuery(sql, objs...)
	if err != nil {
		logs.Print("GroupList Query error", err.Error())
		code = errDBQueryFailed
		msg = err.Error()
		return
	}

	groups := make([]group, 0)
	var count = 0
	for rows.Next() {
		count++
		var gid string
		var icon string
		var nickname string
		err = rows.Scan(&gid, &nickname, &icon)
		if err != nil {
			logs.Print("GroupList rows.Scan error", err.Error())
			code = errRowsScan
			msg = err.Error()
			return
		}
		tem := &group{GroupID: gid, Nickname: nickname, GroupIcon: icon}
		groups = append(groups, *tem)
	}
	if count == 0 {
		msg = "该页已经没有数据了"
		return
	}
	res = groups
	msg = "获取群列表成功"
	return
}
